<?php

namespace Core;

use Yaf\Session;
use Helper\StringHelper;

/**
 * yaf网络请求类封装
 * Class Request
 * @package Core
 */
class Request extends \Yaf\Request_Abstract
{

    /**
     * 主机名（含端口）
     * @var string
     */
    protected $host;

    /**
     * 域名（含协议及端口）
     * @var string
     */
    protected $domain;

    /**
     * 子域名
     * @var string
     */
    protected $subDomain;

    /**
     * 当前URL地址
     * @var string
     */
    protected $url;

    /**
     * 基础URL（不包括QUERY_STRING）
     * @var string
     */
    protected $baseUrl;

    /**
     * 当前HEADER参数
     * @var array
     */
    protected $header = [];

    /**
     * 当前GET参数
     * @var array
     */
    protected $get = [];

    /**
     * 当前POST参数
     * @var post
     */
    protected $post = [];


    /**
     * 架构函数
     * @access public
     */
//    public function __construct()
//    {
//    }

    /**
     * 当前请求的host
     * @access public
     * @param bool $strict  true 仅仅获取HOST
     * @return string
     */
    public function host($strict = false)
    {
        if (!$this->host) {
            $this->host = $this->getServer('HTTP_X_REAL_HOST') ?: $this->getServer('HTTP_HOST');
        }
        return true === $strict && strpos($this->host, ':') ? strstr($this->host, ':', true) : $this->host;
    }

    /**
     * 获取当前包含协议、端口的域名
     * @access public
     * @param  bool $port 是否需要去除端口号
     * @return string
     */
    public function domain($port = false)
    {
        $scheme = $this->isSsl() ? 'https' : 'http';
        return $scheme . '://' . $this->host($port);
    }

    /**
     * 获取当前根域名
     * @access public
     * @return string
     */
    public function rootDomain()
    {

        $item  = explode('.', $this->host(true));
        $count = count($item);
        $root  = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0];
        return $root;
    }

    /**
     * 获取当前子域名
     * @access public
     * @return string
     */
    public function subDomain()
    {
        if (is_null($this->subDomain)) {

            $domain = explode('.', $this->host(true), -2);
            $this->subDomain = implode('.', $domain);
        }

        return $this->subDomain;
    }

    /**
     * 获取当前完整URL 包括QUERY_STRING
     * @access public
     * @param  bool $complete 是否包含域名
     * @return string
     */
    public function url($complete = false)
    {
        if (!$this->url) {
            if ($this->isCli()) {
                $this->url = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';
            } elseif ($this->getServer('HTTP_X_REWRITE_URL')) {
                $this->url = $this->getServer('HTTP_X_REWRITE_URL');
            } elseif ($this->getServer('REQUEST_URI')) {
                $this->url = $this->getServer('REQUEST_URI');
            } elseif ($this->getServer('ORIG_PATH_INFO')) {
                $this->url = $this->getServer('ORIG_PATH_INFO') . (!empty($this->getServer('QUERY_STRING')) ? '?' . $this->getServer('QUERY_STRING') : '');
            } else {
                $this->url = '';
            }
        }
        return $complete ? $this->domain() . $this->url : $this->url;
    }

    /**
     * 获取当前URL 不含QUERY_STRING
     * @access public
     * @param  bool     $domain 是否包含域名
     * @return string|$this
     */
    public function baseUrl($domain = false)
    {
        if (!$this->baseUrl) {
            $str           = $this->url();
            $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
        }

        return $domain ? $this->domain() . $this->baseUrl : $this->baseUrl;
    }

    /**
     * 获取当前的Header
     * @access public
     * @param  string   $name header名称
     * @param  string   $default 默认值
     * @return string|array
     */
    public function header($name = '', $default = null)
    {
        if (empty($this->header)) {
            $header = [];
            if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
                $header = $result;
            } else {
                $server = $this->server;
                foreach ($server as $key => $val) {
                    if (0 === strpos($key, 'HTTP_')) {
                        $key          = str_replace('_', '-', strtolower(substr($key, 5)));
                        $header[$key] = $val;
                    }
                }
                if (isset($server['CONTENT_TYPE'])) {
                    $header['content-type'] = $server['CONTENT_TYPE'];
                }
                if (isset($server['CONTENT_LENGTH'])) {
                    $header['content-length'] = $server['CONTENT_LENGTH'];
                }
            }
            $this->header = array_change_key_case($header);
        }

        if ('' === $name) {
            return $this->header;
        }

        $name = str_replace('_', '-', strtolower($name));

        return isset($this->header[$name]) ? $this->header[$name] : $default;
    }

    /**
     * 获取get参数
     * @param string $name
     * @param  $default
     * @param bool $filter
     * @return array|mixed|string
     */
    public function get($name = '', $default = null, $filter = true)
    {
        if ( empty($this->get) ) {
            $this->get = $_GET;
        }
        if( empty($name) ){
            $params = $this->get;
        }else{
            if( !isset($this->get[$name]) ){
                return $default;
            }
            $params = $this->get[$name];
        }
         return $filter ? StringHelper::filterInput($params) : $params;
    }

    /**
     * 获取post参数
     * @param string $name
     * @param $default
     * @param bool $filter
     * @return array|mixed|string
     */
    public function post($name = '', $default = null, $filter = true)
    {

        if ( empty($this->post) ) {
            $this->post = $_POST;
        }
        if( empty($name) ){
            $params = $this->post;
        }else{
            if( !isset($this->post[$name]) ){
                return $default;
            }
            $params = $this->post[$name];
        }
        return $filter ? StringHelper::filterInput($params) : $params;
    }

    /**
     * 获取session
     * @param $name
     * @return mixedhuo
     */
    public function getSession($name)
    {
        return Session::getInstance()->__get($name);
    }


    /**
     * 设置session
     * @param $name
     * @param $val
     */
    public function setSession($name, $val)
    {
        return Session::getInstance()->__set($name, $val);
    }

    /**
     * 清除session
     * @param $name
     * @return mixed
     */
    public function unsetSession($name)
    {
        return Session::getInstance()->__unset($name);
    }

    /**
     * 设置cookie
     * @param $name
     * @param $value
     * @param int $expire
     * @param string $path
     * @param string $domain
     */
    public function setCookie($name, $value, $expire = 3600, $path = '/', $domain = '')
    {
        setCookie($name, $value, CUR_TIMESTAMP + $expire, $path, $domain);
    }

    /**
     * 获取cookie
     * @param $name
     * @return string
     */
    public function getCookie($name)
    {
        return trim($_COOKIE[$name]);
    }

    /**
     * 清除cookie
     * @param $key
     */
    public function clearCookie($name)
    {
        $this->setCookie($name, '');
    }

    /**
     * 当前是否ssl
     * @access public
     * @return bool
     */
    public function isSsl()
    {
        if ($this->getServer('HTTPS') && ('1' == $this->getServer('HTTPS') || 'on' == strtolower($this->getServer('HTTPS')))) {
            return true;
        } elseif ('https' == $this->getServer('REQUEST_SCHEME')) {
            return true;
        } elseif ('443' == $this->getServer('SERVER_PORT')) {
            return true;
        } elseif ('https' == $this->getServer('HTTP_X_FORWARDED_PROTO')) {
            return true;
        }

        return false;
    }

    /**
     * 当前是否Ajax请求
     * @access public
     * @param  bool $ajax  true 获取原始ajax请求
     * @return bool
     */
    public function isAjax($ajax = false)
    {
        $value  = $this->getServer('HTTP_X_REQUESTED_WITH');
        $result = 'xmlhttprequest' == strtolower($value) ? true : false;
        if (true === $ajax) {
            return $result;
        }
        return $result;
    }

    /**
     * 检测是否使用手机访问
     * @access public
     * @return bool
     */
    public function isMobile()
    {
        if ($this->getServer('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
            return true;
        } elseif ($this->getServer('HTTP_ACCEPT') && strpos(strtoupper($this->getServer('HTTP_ACCEPT')), "VND.WAP.WML")) {
            return true;
        } elseif ($this->getServer('HTTP_X_WAP_PROFILE') || $this->getServer('HTTP_PROFILE')) {
            return true;
        } elseif ($this->getServer('HTTP_USER_AGENT') && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $this->getServer('HTTP_USER_AGENT'))) {
            return true;
        }
        return false;
    }


}